package com.ls.fw.config.zookeeper.beans;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.apache.zookeeper.common.X509Exception.SSLContextException;

import com.ls.fw.config.zookeeper.FourLetterWordMain;

/**      
 */
public class WordsCommand {
	
	public static String[] getResultArray(ZkServerInfo serverInfo, CommandConstEnum commandConstEnum) throws SSLContextException{
		String[] resultArray = null;
		try {
			String cmdResult = FourLetterWordMain.send4LetterWord(serverInfo.getIp(), serverInfo.getPort(), commandConstEnum.getVal());
			if (StringUtils.isNotBlank(cmdResult)) {
				resultArray = cmdResult.split("\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return resultArray;
	}
	
	/**
	 * 四字命令stat
	 * @param serverInfo
	 * @return
	 * @throws SSLContextException 
	 */
	public static ResultStat stat(ZkServerInfo serverInfo) throws SSLContextException{
		String[] resultArray = getResultArray(serverInfo, CommandConstEnum.STAT);
		if (resultArray != null) {
			ResultStat resultStat = new ResultStat();
			for (String rs : resultArray){
				if (rs.indexOf("Zookeeper version:") != -1) {
					resultStat.setZookeeperVersion(rs.replace("Zookeeper version:", "").trim());
				}else if (rs.indexOf("Mode:") != -1) {
					resultStat.setMode(StringUtils.deleteWhitespace(rs.replace("Mode:", "")));
				}else if (rs.indexOf("Connections:") != -1) {
					resultStat.setConnections(Integer.parseInt(StringUtils.deleteWhitespace(rs.replace("Connections:", ""))));
				}else if (rs.indexOf("Node count:") != -1) {
					resultStat.setNodeCount(Integer.parseInt(StringUtils.deleteWhitespace(rs.replace("Node count:", ""))));
				}
			}
			return resultStat;
		}
		return null;
	}
	/**
	 * 四字命令ruok
	 * @param serverInfo
	 * @return
	 * @throws SSLContextException 
	 */
	public static ResultRuok ruok(ZkServerInfo serverInfo) throws SSLContextException{
		String[] resultArray = getResultArray(serverInfo, CommandConstEnum.RUOK);
		if (resultArray != null) {
			ResultRuok resultRuok = new ResultRuok();
			for (String rs : resultArray){
				if (rs.indexOf("imok") != -1) {
					resultRuok.setImok(rs.trim());
				}
			}
			return resultRuok;
		}
		return null;
	}
	/**
	 * 四字命令conf
	 * @param serverInfo
	 * @return
	 * @throws IOException 
	 * @throws SSLContextException 
	 */
	public static String conf(ZkServerInfo serverInfo) throws IOException, SSLContextException{
		String cmdResult = FourLetterWordMain.send4LetterWord(serverInfo.getIp(), serverInfo.getPort(), CommandConstEnum.CONF.getVal());
		return cmdResult;
	}
	
}
